<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in searchSuggestionDate"
      :key="index"
      @click="$emit('search',text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearch } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      searchSuggestionDate: []
      // texts: ''
    }
  },
  components: {
    // eslint-disable-next-line vue/no-unused-components
    getSearch
  },
  // 监听 searchText变化时触发
  watch: {
    searchText: {
      // handler (value) {
      //   this.lodaSearch(value)
      // },
      handler: debounce(function (value) {
        this.lodaSearch(value)
      }, 1000),
      // 被触发只时立即调用
      immediate: true
    }
  },
  methods: {
    async lodaSearch (q) {
      try {
        const { data } = await getSearch(q)
        this.searchSuggestionDate = data.data.options
        console.log(this.searchText, 999)
      } catch (err) {
        this.$toast('数据请求失败，请稍后重试')
      }
    },
    highlight (text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
    // 测试$emit
    // onEmit (text) {
    //   console.log(text, 888)
    //   this.texts = text
    //   this.$emit('search', this.texts)
    // }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/.active {
    color: red;
  }
}
</style>
